﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using mobileS.Resources;
using Windows.System;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using System.IO.IsolatedStorage;

namespace mobileS
{
    public class UserSet
    {
        public int Id { get; set; }

        [JsonProperty(PropertyName = "Email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "SocialId")]
        public string SocialId { get; set; }

        [JsonProperty(PropertyName = "Name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "Admin")]
        public bool Admin { get; set; }
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // MobileServiceCollectionView implements ICollectionView (useful for databinding to lists) and 
        // is integrated with your Mobile Service to make it easy to bind your data to the ListView
        private MobileServiceCollection<UserSet, UserSet> items;

        private MobileServiceUser user;

        private IMobileServiceTable<UserSet> userSetTable = App.MobileService.GetTable<UserSet>();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            //this.Loaded += MainPage_Loaded;
        }

        //async void MainPage_Loaded(object sender, RoutedEventArgs e)
        //{
        //    //await Authenticate();
        //    //RefreshTodoItems();
        //}

        # region Location
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
            {
                // User has opted in or out of Location
                return;
            }
            else
            {
                MessageBoxResult result =
                    MessageBox.Show("This app accesses your phone's location. Is that ok?",
                    "Location",
                    MessageBoxButton.OKCancel);

                if (result == MessageBoxResult.OK)
                {
                    IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
                }
                else
                {
                    IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
                }

                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private async void OneShotLocation_Click(object sender, RoutedEventArgs e)
        {

            if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true)
            {
                // The user has opted out of Location.
                return;
            }

            Geolocator geolocator = new Geolocator();
            geolocator.DesiredAccuracyInMeters = 50;

            try
            {
                Geoposition geoposition = await geolocator.GetGeopositionAsync(
                    maximumAge: TimeSpan.FromMinutes(5),
                    timeout: TimeSpan.FromSeconds(10)
                    );

                LatitudeTextBlock.Text = geoposition.Coordinate.Latitude.ToString("0.00");
                LongitudeTextBlock.Text = geoposition.Coordinate.Longitude.ToString("0.00");
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x80004004)
                {
                    // the application does not have the right capability or the location master switch is off
                    StatusTextBlock.Text = "location  is disabled in phone settings.";
                }
                //else
                {
                    // something else happened acquring the location
                }
            }
        }

        #endregion


        private async System.Threading.Tasks.Task Authenticate()
        {
            while (user == null)
            {
                string message = string.Empty;
                bool registeredOl4Rent = true;
                try
                {
                    registeredOl4Rent = true;
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
                    //
                    MobileServiceCollection<UserSet, UserSet> usr = await userSetTable.Where(usrAux => usrAux.SocialId == user.UserId).ToCollectionAsync();
                    if (usr.Count == 0)
                    {
                        user = null;
                        registeredOl4Rent = false;
                        message = string.Format("Debes registrarte en ol4rent.com antes de poder a esta aplicación!\nThat how Azure works... =(");
                    }
                    else
                    {
                        message = string.Format("Bienvenido " + usr.First().Name + "!");
                    }
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
                MessageBox.Show(message);
                if (!registeredOl4Rent)
                {
                    await Launcher.LaunchUriAsync(new Uri("http://www.ol4rent.com"));
                }
            }
        }

        //private async void InsertTodoItem(UserSet todoItem)
        //{
        //    // This code inserts a new TodoItem into the database. When the operation completes
        //    // and Mobile Services has assigned an Id, the item is added to the CollectionView
        //    await userSetTable.InsertAsync(todoItem);
        //    items.Add(todoItem);
        //}

        private async void RefreshTodoItems()
        {
            // This code refreshes the entries in the list view be querying the TodoItems table.
            // The query excludes completed TodoItems
            try
            {
                items = await userSetTable.ToCollectionAsync();
                    //.Where(todoItem => todoItem.Complete == false)
            }
            catch (MobileServiceInvalidOperationException e)
            {
                MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
            }

            ListItems.ItemsSource = items;
        }

        private async void UpdateCheckedTodoItem(UserSet item)
        {
            // This code takes a freshly completed TodoItem and updates the database. When the MobileService 
            // responds, the item is removed from the list 
            await userSetTable.UpdateAsync(item);
            items.Remove(item);
        }

        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            RefreshTodoItems();
        }

        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            var todoItem = new UserSet { Email = TodoInput.Text };
            todoItem.SocialId = "soyUnSocialId";
            todoItem.Name = "soyUnName";
            todoItem.Admin = false;
            //InsertTodoItem(todoItem);
        }

        private void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            UserSet item = cb.DataContext as UserSet;
            //item.Complete = true;
            item.Admin = true;
            UpdateCheckedTodoItem(item);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SitesList.xaml", UriKind.Relative));
        }
    }
}